package com.whcoding.multithreading.util;

import cn.hutool.core.collection.CollectionUtil;
import com.whcoding.multithreading.thredpool.ThreadPoolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * @author Administrator
 */
public class ThreadSaveUtil<T> {

    private static final Logger log = LoggerFactory.getLogger(ThreadSaveUtil.class);

    public void threadMethod(List<T> updateList) {
        // 初始化线程池, 参数一定要一定要一定要调好！！！！
        ExecutorService threadPool = ThreadPoolUtil.createThread(updateList.size());
        List<T> successList=new ArrayList<>(16);
        // 大集合拆分成N个小集合, 这里集合的size可以稍微小一些（这里我用100刚刚好）, 以保证多线程异步执行, 过大容易回到单线程
        List<List<T>> splitNList = SplitListUtils.split(updateList, 100);
        // 记录单个任务的执行次数
        CountDownLatch countDownLatch = new CountDownLatch(splitNList.size());
        // 对拆分的集合进行批量处理, 先拆分的集合, 再多线程执行
        for (List<T> singleList : splitNList) {
            // 线程池执行
            threadPool.execute(new Thread(new Runnable() {
                @Override
                public void run() {
                    for (T entity : singleList) {
                        // 将每一个对象进行数据封装, 并添加到一个用于存储更新数据的list
                        // ......
                        successList.add(entity);
                        // 任务个数 - 1, 直至为0时唤醒await()
                        countDownLatch.countDown();
                    }
                }
            }));
        }
        try {
            // 让当前线程处于阻塞状态，直到锁存器计数为零
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e.getMessage());
        }
        // 通过mybatis的批量插入的方式来进行数据的插入, 这一步还是要做判空
        if (CollectionUtil.isNotEmpty(successList)) {
            batchUpdateEntity(successList);
            log.info("xxxxxxxxxxxxxxx");
        }
    }

    /**
     * 批量更新
     *
     * @param updateList
     */
    private void batchUpdateEntity(List<T> updateList) {

    }

}
